package org.lex.swt;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;

public class ThreadPane extends Composite {

	public ThreadPane(Composite parent) {
		super(parent, SWT.NONE);
		this.initialize();
	}

	private void initialize() {
		this.setLayout(new RowLayout());
		Button sync = new Button(this, SWT.PUSH);
		sync.setText("sync");
		sync.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				new SWTWorker<Object>() {
					@Override
					protected Object doInBackground() throws Exception {
						create("sync").run();
						return null;
					}

					protected void done() {
						System.out.println("Done");
					}
				}.execute();
			}
		});

		Button asyc = new Button(this, SWT.PUSH);
		asyc.setText("asyc");
		asyc.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				Display.getCurrent().asyncExec(create("asyc"));
			}
		});
	}

	private Runnable create(final String title) {
		return new Runnable() {
			public void run() {
				System.out.println("Title: " + title);
				for (int i = 0; i < 3; i++) {
					try {
						Thread.sleep(1000);
						System.out.println(title + " sleep " + i);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}

				System.out.println("===============" + title + " finished");
			}
		};
	}
}
